package com.jintian.smart.kernel.message.service;

import com.google.common.collect.Lists;
import com.jintian.smart.base.api.message.entity.NoticeViewRecordEntity;
import com.jintian.smart.base.api.message.vo.*;
import com.jintian.smart.base.api.system.entity.EmployeeEntity;
import com.jintian.smart.base.api.system.provider.IDepartmentProvider;
import com.jintian.smart.base.api.system.provider.IEmployeeProvider;
import com.jintian.smart.kernel.common.util.SmartBeanUtil;
import com.jintian.smart.kernel.core.domain.ResponseDTO;
import com.jintian.smart.base.api.message.constant.NoticeVisibleRangeDataTypeEnum;
import com.jintian.smart.base.api.message.form.NoticeEmployeeQueryForm;
import com.jintian.smart.base.api.message.form.NoticeViewRecordQueryForm;
import com.jintian.smart.kernel.message.mapper.NoticeMapper;
import com.jintian.smart.kernel.message.mapper.NoticeViewRecordMapper;
import jakarta.annotation.Resource;
import org.apache.dubbo.config.annotation.DubboReference;
import org.beetl.sql.core.page.PageResult;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 员工查看 通知公告
 */
@Service
public class NoticeEmployeeService {
    @Resource
    private NoticeMapper noticeMapper;

    @Resource
    private NoticeService noticeService;

    @Resource
    private NoticeViewRecordMapper noticeViewRecordMapper;

    @DubboReference
    private IDepartmentProvider departmentProvider;

    @DubboReference
    private IEmployeeProvider employeeProvider;


    /**
     * 查询我的 通知、公告清单
     */
    public ResponseDTO<PageResult<NoticeEmployeeVO>> queryList(Long requestEmployeeId, NoticeEmployeeQueryForm noticeEmployeeQueryForm) {
        List<Long> employeeDepartmentIdList = Lists.newArrayList();
        EmployeeEntity employeeEntity = employeeProvider.getById(requestEmployeeId);
        // 如果不是管理员 则获取请求人的 部门及其子部门
        if (employeeEntity.getAdministratorFlag() == 0 && employeeEntity.getDepartmentId() != null) {
            employeeDepartmentIdList = departmentProvider.selfAndChildrenIdList(employeeEntity.getDepartmentId());
        }

        PageResult<NoticeEmployeeVO> noticePage = null;
        //只查询未读的
        if (noticeEmployeeQueryForm.getNotViewFlag() != null && noticeEmployeeQueryForm.getNotViewFlag() == 1) {
            noticePage = noticeMapper.queryEmployeeNotViewNotice(requestEmployeeId,
                    noticeEmployeeQueryForm,
                    employeeDepartmentIdList,
                    0,
                    employeeEntity.getAdministratorFlag(),
                    NoticeVisibleRangeDataTypeEnum.DEPARTMENT.getValue(),
                    NoticeVisibleRangeDataTypeEnum.EMPLOYEE.getValue());
        } else {
            // 查询全部
            noticePage = noticeMapper.queryEmployeeNotice(requestEmployeeId,
                    noticeEmployeeQueryForm,
                    employeeDepartmentIdList,
                    0,
                    employeeEntity.getAdministratorFlag(),
                    NoticeVisibleRangeDataTypeEnum.DEPARTMENT.getValue(),
                    NoticeVisibleRangeDataTypeEnum.EMPLOYEE.getValue());
        }
        // 设置发布日期
        noticePage.getList().forEach(notice -> notice.setPublishDate(notice.getPublishTime().toLocalDate()));

        return ResponseDTO.ok(noticePage);
    }


    /**
     * 查询我的 待查看的 通知、公告清单
     */
    public ResponseDTO<NoticeDetailVO> view(Long requestEmployeeId, Long noticeId, String ip, String userAgent) {
        NoticeUpdateFormVO updateFormVO = noticeService.getUpdateFormVO(noticeId);
        if (updateFormVO == null || Boolean.TRUE.equals(updateFormVO.getDeletedFlag())) {
            return ResponseDTO.userErrorParam("通知公告不存在");
        }

        EmployeeEntity employeeEntity = employeeProvider.getById(requestEmployeeId);
        if (updateFormVO.getAllVisibleFlag() == 0 && !checkVisibleRange(updateFormVO.getVisibleRangeList(), requestEmployeeId, employeeEntity.getDepartmentId())) {
            return ResponseDTO.userErrorParam("对不起，您没有权限查看内容");
        }

        NoticeDetailVO noticeDetailVO = SmartBeanUtil.copy(updateFormVO, NoticeDetailVO.class);
        long viewCount = noticeMapper.viewRecordCount(noticeId, requestEmployeeId);
        if (viewCount == 0) {
//            noticeMapper.insertViewRecord(noticeId, requestEmployeeId, ip, userAgent, 1);
            NoticeViewRecordEntity noticeViewRecordEntity = NoticeViewRecordEntity.builder().
                    noticeId(noticeId).employeeId(requestEmployeeId).firstIp(ip).firstUserAgent(userAgent).pageViewCount(1).build();
            noticeViewRecordMapper.upsert(noticeViewRecordEntity);
            // 该员工对于这个通知是第一次查看 页面浏览量+1 用户浏览量+1
            noticeMapper.updateViewCount(noticeId, 1, 1);
            noticeDetailVO.setPageViewCount(noticeDetailVO.getPageViewCount() + 1);
            noticeDetailVO.setUserViewCount(noticeDetailVO.getUserViewCount() + 1);
        } else {
            noticeMapper.updateViewRecord(noticeId, requestEmployeeId, ip, userAgent);
            // 该员工对于这个通知不是第一次查看 页面浏览量+1 用户浏览量+0
            noticeMapper.updateViewCount(noticeId, 1, 0);
            noticeDetailVO.setPageViewCount(noticeDetailVO.getPageViewCount() + 1);
        }

        return ResponseDTO.ok(noticeDetailVO);
    }

    /**
     * 校验是否有查看权限的范围
     */
    public boolean checkVisibleRange(List<NoticeVisibleRangeVO> visibleRangeList, Long employeeId, Long departmentId) {
        // 员工范围
        boolean anyMatch = visibleRangeList.stream().anyMatch(e -> NoticeVisibleRangeDataTypeEnum.EMPLOYEE.equalsValue(e.getDataType()) && Objects.equals(e.getDataId(), employeeId));
        if (anyMatch) {
            return true;
        }

        //部门范围
        List<Long> visibleDepartmentIdList = visibleRangeList.stream().filter(e -> NoticeVisibleRangeDataTypeEnum.DEPARTMENT.equalsValue(e.getDataType()))
                .map(NoticeVisibleRangeVO::getDataId).collect(Collectors.toList());

        for (Long visibleDepartmentId : visibleDepartmentIdList) {
            List<Long> departmentIdList = departmentProvider.selfAndChildrenIdList(visibleDepartmentId);
            if (departmentIdList.contains(departmentId)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 分页查询  查看记录
     */
    public PageResult<NoticeViewRecordVO> queryViewRecord(NoticeViewRecordQueryForm noticeViewRecordQueryForm) {
        PageResult<NoticeViewRecordVO> noticeViewRecordPage = noticeMapper.queryNoticeViewRecordList(noticeViewRecordQueryForm);
        return noticeViewRecordPage;
    }
}
